package com.pkx.cloud.fse7.expand.group.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.pkx.cloud.fse7.dms.deviceread.entity.DeviceRead;
import com.pkx.cloud.fse7.dms.deviceread.service.DeviceReadService;
import com.pkx.cloud.fse7.dms.monitoring.entity.RemoteOrder;
import com.pkx.cloud.fse7.dms.monitoring.service.RemoteOrderService;
import com.pkx.cloud.fse7.expand.group.entity.DoorGroup;
import com.pkx.cloud.fse7.expand.group.entity.DoorGroupDetail;
import com.pkx.cloud.fse7.expand.group.feign.LinkageFeign;
import com.pkx.cloud.fse7.expand.group.feign.PlanFeign;
import com.pkx.cloud.fse7.expand.group.feign.entity.Yard;
import com.pkx.cloud.fse7.expand.group.repo.DoorGroupMapper;
import com.pkx.cloud.fse7.expand.group.service.DoorGroupDetailService;
import com.pkx.cloud.fse7.expand.group.service.DoorGroupService;
import com.pkx.cloud.whzx.comn.OutRpose;
import com.pkx.cloud.whzx.util.LoginUserUtil;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author chenwg
 * @since 2021-04-09
 */
@Service
@DS("slave")
public class DoorGroupServiceImpl extends ServiceImpl<DoorGroupMapper, DoorGroup> implements DoorGroupService {

    @Resource
    private DoorGroupDetailService groupDetailService;
    @Resource
    private PlanFeign planFeign;
    @Resource
    private DeviceReadService deviceReadService;
    @Resource
    private LinkageFeign linkageFeign;
    @Resource
    private RemoteOrderService remoteOrderService;


    /**
     * 分页列表
     *
     * @param doorGroup
     * @return
     */
    @Override
    public Page<DoorGroup> pageList(Page page, DoorGroup doorGroup) {
        return baseMapper.pageList(page, doorGroup);
    }

    /**
     * 列表查询
     *
     * @param doorGroup
     * @return
     */
    @Override
    public List<DoorGroup> listByEntity(DoorGroup doorGroup) {
        LambdaQueryWrapper<DoorGroup> lambdaQueryWrapper = Wrappers.lambdaQuery(DoorGroup.class);
        return list(lambdaQueryWrapper);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public DoorGroup selectById(String id) {
        return getById(id);
    }

    /**
     * 保存
     *
     * @param doorGroup
     * @return
     */
    @Override
    public Boolean saveDoorGroup(DoorGroup doorGroup) {
        doorGroup.setCreateUserName(LoginUserUtil.getLoginUserName());
        String parentId = doorGroup.getParentId();
        // 获取树完整路径
        Yard yard = planFeign.findYard(parentId).getData();
        String yardId = yard.getYardId();
        String path = yard.getPath();

        String idStr = IdWorker.getIdStr();
        doorGroup.setLevel(yard.getYardLevel() + 1);
        doorGroup.setId(idStr);
        if (StrUtil.isBlank(path)) {
            doorGroup.setPath(yardId + ":" + idStr);
        } else {
            doorGroup.setPath(path + ":" + yardId + ":" + idStr);
        }
        doorGroup.setWeight("999");
        // 保存分组
        save(doorGroup);
        // 保存分组明细
        List<String> detais = doorGroup.getDetails();
        // 获取设备明细
        List<DeviceRead> byRids = deviceReadService.getDmsDevice(detais);
        ArrayList<DoorGroupDetail> doorGroupDetails = Lists.newArrayList();
        byRids.forEach(deviceRead -> {
            DoorGroupDetail doorGroupDetail = new DoorGroupDetail();
            doorGroupDetail.setGroupId(doorGroup.getId());
            doorGroupDetail.setDoorNo(deviceRead.getDoorNo());
            doorGroupDetail.setDevNo(deviceRead.getDevNo());
            doorGroupDetail.setDoorId(deviceRead.getRid());
            doorGroupDetail.setName(deviceRead.getName());
            doorGroupDetail.setDevId(deviceRead.getDevId());
            doorGroupDetail.setRemark(doorGroup.getRemark());
            doorGroupDetails.add(doorGroupDetail);
        });
        return groupDetailService.saveBatch(doorGroupDetails);
    }

    /**
     * 修改
     *
     * @param doorGroup
     * @return
     */
    @Override
    public Boolean modify(DoorGroup doorGroup) {
        String parentId = doorGroup.getParentId();
        // 获取树完整路径
        Yard yard = planFeign.findYard(parentId).getData();
        String path = yard.getPath();
        doorGroup.setLevel(yard.getYardLevel() + 1);
        doorGroup.setPath(path + ":" + doorGroup.getId());
        // 更新分组名称
        updateById(doorGroup);
        // 删除旧的分组明细
        groupDetailService.deleteByGroupId(doorGroup.getId());
        // 添加新的明细
        List<String> detais = doorGroup.getDetails();
        // 获取设备明细
        List<DeviceRead> byRids = deviceReadService.getDmsDevice(detais);
        ArrayList<DoorGroupDetail> doorGroupDetails = Lists.newArrayList();
        byRids.forEach(deviceRead -> {
            DoorGroupDetail doorGroupDetail = new DoorGroupDetail();
            doorGroupDetail.setGroupId(doorGroup.getId());
            doorGroupDetail.setDoorNo(deviceRead.getDoorNo());
            doorGroupDetail.setDevNo(deviceRead.getDevNo());
            doorGroupDetail.setDoorId(deviceRead.getRid());
            doorGroupDetail.setName(deviceRead.getName());
            doorGroupDetail.setDevId(deviceRead.getDevId());
            doorGroupDetail.setRemark(doorGroup.getRemark());
            doorGroupDetails.add(doorGroupDetail);
        });
        return groupDetailService.saveBatch(doorGroupDetails);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deleteById(String id) {
        removeById(id);
        return groupDetailService.deleteByGroupId(id);
    }

    @Override
    public List getYardList() {
        // 场地列表
        List<Yard> data = planFeign.getYardList().getData();
        // 到层级 即3级
        List<Yard> yardList = data.stream()
                .filter(yard -> yard.getYardLevel() <= 3)
                .collect(Collectors.toList());
        if (yardList.isEmpty()) {
            log.error("场地列表为空");
            return null;
        }
        // 获取分组列表
        List<DoorGroup> doorGroups = listByEntity(null);
        doorGroups.forEach(group -> {
            Yard yard = new Yard();
            yard.setYardLevel(group.getLevel());
            yard.setName(group.getGroupName());
            yard.setYardId(group.getId());
            yard.setPatUuid(group.getParentId());
            yard.setEnabled("0");
            yard.setWeight(group.getWeight());
            yardList.add(yard);
        });
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setNameKey("label");
        treeNodeConfig.setWeightKey("weight");
        // 最大递归深度
        treeNodeConfig.setDeep(4);
        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(yardList, "", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getYardId());
                    tree.setParentId(treeNode.getPatUuid());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    tree.putExtra("enabled", treeNode.getEnabled());
                    tree.putExtra("yardLevel", treeNode.getYardLevel());
                    tree.putExtra("code", treeNode.getCode());
                });
        leaf(treeNodes);
        return treeNodes;
    }

    @Override
    public List getDeviceTree() {
        // 场地列表
        List<Yard> data = planFeign.getYardList().getData();
        // 到层级 即3级
        List<Yard> yardList = data.stream()
                .filter(yard -> yard.getYardLevel() <= 3)
                .collect(Collectors.toList());
        if (yardList.isEmpty()) {
            log.error("场地列表为空");
            return null;
        }
        // 获取设备列表
        List<DeviceRead> deviceReads = deviceReadService.listByEntity(null);
        deviceReads.forEach(device -> {
            Yard yard = new Yard();
            yard.setYardLevel(4);
            yard.setName(device.getName());
            yard.setYardId(device.getRid());
            yard.setPatUuid(device.getDoorAreaId());
            yard.setEnabled("0");
            yard.setWeight("999");
            yardList.add(yard);
        });
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setNameKey("label");
        treeNodeConfig.setWeightKey("weight");
        // 最大递归深度
        treeNodeConfig.setDeep(4);
        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(yardList, "", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getYardId());
                    tree.setParentId(treeNode.getPatUuid());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    tree.putExtra("enabled", treeNode.getEnabled());
                    tree.putExtra("yardLevel", treeNode.getYardLevel());
                    tree.putExtra("code", treeNode.getCode());
                });
        leaf(treeNodes);
        return treeNodes;
    }

    /**
     * 叶子节点
     *
     * @param list
     * @return
     */
    public List<Tree<String>> leaf(List<Tree<String>> list) {
        list.stream().forEach(tree -> {
            if (Objects.isNull(tree.getChildren()) || tree.getChildren().isEmpty()) {
                tree.putExtra("leaf", true);
            } else {
                tree.putExtra("leaf", false);
                leaf(tree.getChildren());
            }
        });
        return list;
    }

    @Override
    public List getGroupByPath(String path) {
        List<String> strings = Arrays.asList(path.split(","));
        return baseMapper.getGroupByPath(strings);
    }

    @Override
    public Boolean execute(String triggerId, List<String> list) {
        // 发送开始信息
        sendMessage(triggerId, 0, "门禁设备开始执行");
        // 根据分组list 获取分组详情,获取门禁列表
        List<DoorGroupDetail> allByGroupIds = groupDetailService.getAllByGroupIds(list);
        // 调用开门接口
        allByGroupIds.forEach(deviceRead -> {
            RemoteOrder remoteOrder = new RemoteOrder();
            remoteOrder.setSubSystem(2);
            remoteOrder.setOrderDate(new Date());
            remoteOrder.setIsLegal(true);
            remoteOrder.setIsLogHandGate(true);
            remoteOrder.setOrder(1);
            remoteOrder.setDevId(deviceRead.getDevId());
            remoteOrder.setParameter(String.valueOf(deviceRead.getDoorNo()));
            remoteOrderService.open(remoteOrder);
        });
        // 发送结束信息
        sendMessage(triggerId, 1, "门禁设备执行结束");
        return true;
    }

    private void sendMessage(String triggerId, Integer status, String remark) {
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("triggerId", triggerId);
        map.put("groupType", 1);
        map.put("remark", remark);
        map.put("status", status);
        linkageFeign.addMessage(map);
    }

}
